﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using com.pro2e.console.service.auth.dao;
using com.pro2e.console.service.auth.vo;
using System.Collections.Generic;
using System.Collections;
using com.pro2e.web.config.init;
using com.pro2e.console.core.valueobject;

/// <summary>
/// CustomSqlRoleProvider 的摘要描述
/// </summary>
/// 

namespace com.pro2e.console.service.auth
{
    public class CustomHBNRoleProvider : RoleProvider
    {

        LoginRoleDao loginRoleDao = new LoginRoleDao();
        LoginUserDao loginUserDao = new LoginUserDao();
       
        public override void AddUsersToRoles(string[] userIds, string[] roleNames)
        {
            foreach (string userId in userIds)
            {
                foreach (string roleName in roleNames)
                {

                    if (!IsUserInRole(userId, roleName))
                    {                        
                                      
                       LoginRole loginRole = loginRoleDao.GetVOsByName(roleName)[0];
                       loginRole.BelongUsers.Add(loginUserDao.DaoGetVOById<LoginUser>(userId));

                       GetHBNSession().Update(loginRole);
                    }
                }
            }
        }



        public override void RemoveUsersFromRoles(string[] userIds, string[] roleNames)
        {
            lock (typeof(CustomHBNRoleProvider))
            {
                foreach (string userId in userIds)
                {
                    foreach (string roleName in roleNames)
                    {
                        LoginRole loginRole = loginRoleDao.GetVOsByName(roleName)[0];

                        loginRole.BelongUsers.Remove(loginUserDao.DaoGetVOById<LoginUser>(userId));

                        GetHBNSession().Update(loginRole);
                    }
                }
            }

        }

        /// <summary>
        /// 
        /// </summary>
        public override string ApplicationName
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="roleName"></param>
        public override void CreateRole(string roleName)
        {
            if (!RoleExists(roleName))
            {
                LoginRole loginRole = new LoginRole();
                loginRole.RoleName = roleName;
                loginRole.LoweredRoleName = roleName.ToLower();
                loginRoleDao.DaoInsert(loginRole);
            }
        }


        /// <summary>
        /// 刪除的角色名稱
        /// </summary>
        /// <param name="roleName">要刪除的角色名稱。</param>
        /// <param name="throwOnPopulatedRole">如果為 true，就會在 roleName 具有一或多個成員時擲回例外狀況。</param>
        /// <returns>如果 roleName 已從資料來源中刪除，則為 true，否則為 false</returns>
        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            IList<LoginRole> loginRoles = loginRoleDao.GetVOsByName(roleName);

            if (throwOnPopulatedRole && loginRoles.Count>1)
            {
                throw new System.Configuration.Provider.ProviderException("roleName is more than one");
            }
            else 
            {
                loginRoleDao.DaoDelete(loginRoles[0]);
                return true;
            }
            
        }
        /// <summary>
        /// 取得指定角色中的使用者清單，其中使用者名稱包含要符合的指定使用者名稱
        /// </summary>
        /// <param name="roleName">要搜尋的角色</param>
        /// <param name="usernameToMatch">要搜尋的使用者名稱</param>
        /// <returns>字串陣列，包含所有使用者的名稱，這些使用者的使用者名稱符合 userIdToMatch，而且是指定角色的成員。</returns>
        public override string[] FindUsersInRole(string roleName, string userIdToMatch)
        {
            //找出roleId

            List<string> userNameList = new List<string>();
            
            IList<LoginRole> roles = loginRoleDao.GetVOsByName(roleName);

            


            if (roles == null || roles.Count == 0)
            {
                return null;
            }
            else 
            {

                foreach (LoginRole role in roles) 
                {
                    IList<LoginUser> users = role.BelongUsers;

                  
                    if (users != null && users.Count > 0)
                    {
                        foreach (LoginUser user in users)
                        {
                            userNameList.Add(user.UserId);
                        }
                    }
                    else
                    {
                        return null;
                    }          
                }                           
            }

            return userNameList.ToArray();

        }

        public override string[] GetAllRoles()
        {
            IList<LoginRole> roles = loginRoleDao.DaoGetAllVO<LoginRole>();
            List<String> roleNameList = new List<string>();

            foreach (LoginRole role in roles) 
            {
                roleNameList.Add(role.RoleName);
            }

            if (roleNameList.Count > 0)
            {
                return roleNameList.ToArray();
            }
            else
            {
                return null;
            }
        }

        public override string[] GetRolesForUser(string userId)
        {
            List<string> resultList = new List<string>();

            LoginUser loginUser = loginUserDao.DaoGetVOById<LoginUser>(userId);

         
                foreach (LoginRole role in loginUser.BelongRoles) 
                {
                  
                    resultList.Add(role.RoleName);
                }
           
            return resultList.ToArray();
        }

       

        public override string[] GetUsersInRole(string roleName)
        {
            IList<LoginRole> loginRoles = loginRoleDao.GetVOsByName(roleName);

            List<string> users = new List<string>();
            if (loginRoles != null && loginRoles.Count > 0) 
            {
                foreach (LoginRole role in loginRoles) 
                {

                    foreach (LoginUser loginUser in role.BelongUsers) 
                    {

                        users.Add(loginUser.UserId);
                    }                                     
                }
            }

            if (users.Count > 0)
            {
                return users.ToArray();
            }
            else { return null; }
            
        }

        public override bool IsUserInRole(string userId, string roleName)
        {
            LoginUser loginUser = loginUserDao.DaoGetVOById<LoginUser>(userId);

            foreach (LoginRole role in loginUser.BelongRoles) 
            {
                if(role.RoleName.Equals(roleName))
                {
                    return true;
                }
            }
            return false;                   
        }
      
        public override bool RoleExists(string roleName)
        {
            IList<LoginRole> loginRoles = loginRoleDao.GetVOsByName(roleName);
            if (loginRoles != null && loginRoles.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }



        #region IDao 成員

        public NHibernate.ISession GetHBNSession()
        {
            return WebApplication.SessionFactory.GetCurrentSession();
        }

        #endregion
    }
}